package com.meida.module.bus.provider.controller.srmsys;

import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.springmvc.base.BaseController;
import com.meida.module.bus.client.entity.BusMaterial;
import com.meida.module.bus.client.entity.BusMaterialPackage;
import com.meida.module.bus.client.entity.BusMaterialPackage100;
import com.meida.module.bus.client.entity.BusSupplier;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmContracts;
import com.meida.module.bus.client.entity.srmapi.basedata.SrmVendor;
import com.meida.module.bus.provider.service.*;
import com.meida.module.bus.provider.service.srmservice.SrmContractsService;
import com.meida.module.bus.provider.service.srmservice.SrmSqlserCommonService;
import com.meida.module.bus.provider.service.srmservice.SynchroSrmToPmsService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.meida.common.mybatis.model.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DELETE;

import org.springframework.web.bind.annotation.RestController;

/**
 * srm合同主数据控制器
 *
 * @author flyme
 * @date 2020-12-21
 */
@RestController
@RequestMapping("/bus/srmContracts/")
public class SrmContractsController extends BaseController<SrmContractsService, SrmContracts> {

    @Autowired
    private SynchroSrmToPmsService synchroSrmToPmsService;

    @Autowired
    private BusMaterialService busMaterialService;

    @Autowired
    private BusProjectService busProjectService;

    @Autowired
    private BusSupplierService busSupplierService;
    @Autowired
    private SrmSqlserCommonService srmSqlserCommonService;

    @ApiOperation(value = "srm合同主数据-分页列表", notes = "srm合同主数据分页列表")
    @GetMapping(value = "page")
    public ResultBody pageList(@RequestParam(required = false) Map params) {
//        synchroSrmToPmsService.sync_contracts(Maps.newHashMap());
        return bizService.pageList(params);
    }

    @ApiOperation(value = "srm合同主数据-列表", notes = "srm合同主数据列表")
    @GetMapping(value = "list")
    public ResultBody list(@RequestParam(required = false) Map params) {
        return bizService.listEntityMap(params);
    }

    @ApiOperation(value = "srm合同主数据-添加", notes = "添加srm合同主数据")
    @PostMapping(value = "save")
    public ResultBody save(@RequestParam(required = false) Map params) {
        return bizService.add(params);
    }

    @ApiOperation(value = "srm合同主数据-更新", notes = "更新srm合同主数据")
    @PostMapping(value = "update")
    public ResultBody update(@RequestParam(required = false) Map params) {
        return bizService.edit(params);
    }

    @ApiOperation(value = "srm合同主数据-删除", notes = "删除srm合同主数据")
    @PostMapping(value = "remove")
    public ResultBody remove(@RequestParam(required = false) Map params) {
        return bizService.delete(params);
    }


    @ApiOperation(value = "srm合同主数据-详情", notes = "srm合同主数据详情")
    @GetMapping(value = "get")
    public ResultBody get(@RequestParam(required = false) Map params) {
        return bizService.get(params);
    }

    /**
     * 导出srm合同主数据统计
     *
     * @param params
     * @param request
     * @param response
     */
    @PostMapping(value = "export")
    public void export(@RequestParam(required = false) Map params, HttpServletRequest request, HttpServletResponse response) {
        bizService.export(params, request, response, "srm合同主数据统计", "srm合同主数据统计表");
    }

    @ApiOperation(value = "获取单一合同信息", notes = "获取单一合同信息")
    @GetMapping(value = "getSingleInfo")
    public ResultBody getSingleInfo(Long contractId) {
        ResultBody rs = new ResultBody();
        rs.data(bizService.getById(contractId));
        return rs;
    }

    @ApiOperation(value = "同步供应商信息", notes = "同步供应商信息")
    @GetMapping(value = "syncVendorInfo")
    public ResultBody syncVendorInfo() {
        //3.添加定时任务
        //或直接指定时间间隔，例如：5秒
        //@Scheduled(fixedRate=5000)
        System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        StaticLog.info("syncVendorInfoFromSrm---手动执行-start");
        List<BusSupplier> busSupplierList = busSupplierService.list();
        List<SrmVendor> srmVendorList = srmSqlserCommonService.getSrmVendor(Maps.newHashMap());
        if (0 < srmVendorList.size() && 0 < busSupplierList.size()) {
            StaticLog.info("syncVendorInfoFromSrm----判断开始");

            List<BusSupplier> busSuppliersForIns = Lists.newArrayList();
            List<BusSupplier> busSuppliersForUpd = Lists.newArrayList();
            srmVendorList.stream().forEach(srmVendorObj -> {
                if (null != srmVendorObj.getErpSynState() && BigDecimal.ONE.compareTo(srmVendorObj.getErpSynState()) == 0) {
                    if (!busSupplierList.stream().anyMatch(busSupplier -> busSupplier.getSupplierCode().equals(srmVendorObj.getVendorCode()))) {
                        BusSupplier busSupplier = new BusSupplier();
                        busSupplier.setSupplierCode(srmVendorObj.getVendorCode());
                        busSupplier.setSupplierName(srmVendorObj.getVendorName());
                        StaticLog.info("存在插入");
                        StaticLog.info("syncVendorInfoFromSrm--ins--srmVendorObj.getVendorCode()：" + srmVendorObj.getVendorCode());
                        StaticLog.info("syncVendorInfoFromSrm--ins--srmVendorObj.getVendorName()：" + srmVendorObj.getVendorName());
                        busSuppliersForIns.add(busSupplier);
                    } else {
                        BusSupplier busSupplierExists = busSupplierList.stream().filter(busSupplier -> busSupplier.getSupplierCode().equals(srmVendorObj.getVendorCode())).findFirst().get();
                        if (!busSupplierExists.getSupplierName().equals(srmVendorObj.getVendorName())) {
                            busSupplierExists.setSupplierName(srmVendorObj.getVendorName());
                            StaticLog.info("存在更新");
                            StaticLog.info("syncVendorInfoFromSrm--upd--busSupplierExists.getSupplierName()：" + busSupplierExists.getSupplierName());
                            StaticLog.info("syncVendorInfoFromSrm--upd--busSupplierExists.getSupplierCode()：" + busSupplierExists.getSupplierCode());
                            StaticLog.info("syncVendorInfoFromSrm--upd--srmVendorObj.getVendorCode()：" + srmVendorObj.getVendorCode());
                            StaticLog.info("syncVendorInfoFromSrm--upd--srmVendorObj.getVendorName()：" + srmVendorObj.getVendorName());
                            busSuppliersForUpd.add(busSupplierExists);
                        }
                    }
                }
            });
            if (0 < busSuppliersForIns.size()) {
                busSupplierService.saveBatch(busSuppliersForIns);
            }
            if (0 < busSuppliersForUpd.size()) {
                busSupplierService.updateBatchById(busSuppliersForUpd);
            }
        } else if (0 == busSupplierList.size()) {
            StaticLog.info("syncVendorInfoFromSrm--全量插入--判断开始");
            List<BusSupplier> busSuppliersForIns = Lists.newArrayList();
            srmVendorList.stream().forEach(srmVendorObj -> {
                if (null != srmVendorObj.getErpSynState() && BigDecimal.ONE.compareTo(srmVendorObj.getErpSynState()) == 0) {
                    BusSupplier busSupplier = new BusSupplier();
                    busSupplier.setSupplierCode(srmVendorObj.getVendorCode());
                    busSupplier.setSupplierName(srmVendorObj.getVendorName());
                    StaticLog.info("存在插入");
                    StaticLog.info("syncVendorInfoFromSrm--ins--srmVendorObj.getVendorCode()：" + srmVendorObj.getVendorCode());
                    StaticLog.info("syncVendorInfoFromSrm--ins--srmVendorObj.getVendorName()：" + srmVendorObj.getVendorName());
                    busSuppliersForIns.add(busSupplier);
                }
            });
            if (0 < busSuppliersForIns.size()) {
                busSupplierService.saveBatch(busSuppliersForIns);
            }
        }
        StaticLog.info("syncVendorInfoFromSrm--手动执行--end");
        return ResultBody.ok();
    }

    @ApiOperation(value = "获取测试项目", notes = "获取测试项目")
    @GetMapping(value = "getProjectLists")
    public ResultBody getProjectLists() {
        CriteriaQuery<BusMaterial> busMaterialCriteriaQuery = new CriteriaQuery(BusMaterial.class);
        busMaterialCriteriaQuery.select("DISTINCT projectId");
        List<BusMaterial> busMaterialList = busMaterialService.list(busMaterialCriteriaQuery);
        List<Long> projectIds = Lists.newArrayList();
        busMaterialList.stream().forEach(busMaterialObj -> {
            projectIds.add(busMaterialObj.getProjectId());
        });
        if (0 == projectIds.size()) {
            return ResultBody.ok();
        }

        return ResultBody.ok(busProjectService.listByIds(projectIds));
    }

    @ApiOperation(value = "获取测试项目", notes = "获取测试项目")
    @GetMapping(value = "delProject")
    public ResultBody delProject(Long projectId) {
        if (null == projectId) {
            return ResultBody.failed();
        }

//        delete from bus_material where projectId = 95;
        bizService.del_tbl_data("bus_material", projectId);
//        delete from bus_material_package100 where projectId = 95;
        bizService.del_tbl_data("bus_material_package100", projectId);
//        delete from bus_material_package200 where projectId = 95;
        bizService.del_tbl_data("bus_material_package200", projectId);
//        delete from bus_material_plan100 where projectId = 95;
        bizService.del_tbl_data("bus_material_plan100", projectId);
//        delete from bus_material_plan200 where projectId = 95;
        bizService.del_tbl_data("bus_material_plan200", projectId);
//        delete from bus_version where projectId = 95;
        bizService.del_tbl_data("bus_version", projectId);
//        delete from bus_report where projectId = 95;
        bizService.del_tbl_data("bus_report", projectId);
//        delete from bus_report_outward where projectId = 95;
        bizService.del_tbl_data("bus_report_outward", projectId);
//        delete from bus_purchase where projectId = 95;
        bizService.del_tbl_data("bus_purchase", projectId);
//        delete from bus_purchase_details where projectId = 95;
        bizService.del_tbl_data("bus_purchase_details", projectId);
//        delete from bus_project_supplier where projectId = 95;
        bizService.del_tbl_data("bus_project_supplier", projectId);

//        DELETE from bus_material_srm where projectId = 95;
        bizService.del_tbl_data("bus_material_srm", projectId);
//        DELETE from bus_material_srm_sub where projectId = 95;
        bizService.del_tbl_data("bus_material_srm_sub", projectId);
//        DELETE from bus_project_pack_sync_srm where projectId = 95;
        bizService.del_tbl_data("bus_project_pack_sync_srm", projectId);
//        DELETE from bus_oa_approval_sync where projectId = 95;
        bizService.del_tbl_data("bus_oa_approval_sync", projectId);
//        UPDATE bus_project set versionId = null , versionpackageId = null,archive200packge = null, version100 = null where projectId = 95;
        bizService.update_project(projectId);

        return ResultBody.ok();
    }

}
